package com.manor.main.fragment.user

import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.manor.common.CommonAppConfig
import com.manor.common.Constants
import com.manor.common.custom.DrawableTextView
import com.manor.common.fragment.BaseFragment
import com.manor.common.http.HttpCallback
import com.manor.common.http.PitUtil
import com.manor.common.utils.ClickUtil
import com.manor.common.utils.RouteUtil
import com.manor.common.utils.ToastUtil
import com.manor.common.utils.WordUtil
import com.manor.common.utils.*
import com.manor.dynamic.activity.DynamicDetailsActivity
import com.manor.dynamic.adapter.NewCirclePopAdapter
import com.manor.dynamic.bean.CommunityDynamicBean
import com.manor.dynamic.http.DynamicHttpUtil
import com.manor.dynamic.views.AudioMp3View
import com.manor.main.R
import com.manor.main.activity.UserCenterActivity
import com.manor.main.adapter.NewDyNamicAdapter
import com.tencent.rtmp.ITXVodPlayListener
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.TXVodPlayer
import com.tencent.rtmp.ui.TXCloudVideoView
import kotlinx.android.synthetic.main.fragment_user_dynamic.*
import java.util.*

/**
 * 我的社区动态
 *
 *
 * @date  2020/7/14  18:05
 * @version 1.0
 */
class UserDynamicFragment : BaseFragment() {
    private var mUid = ""
    internal var pageNum = 1
    private var firstVisibleItem = 0
    private var lastVisibleItem = 0
    private var visibleCount = 0
    private var my_position: Int = 0
    var flvUrl: String = ""
    private  var mPlayer: TXVodPlayer? = null

    var communityDynamicBeans: MutableList<CommunityDynamicBean> = ArrayList()
    var is_shuaxin: Boolean = true
    private val arrayList = ArrayList<String>()
    lateinit var communityDynamicAdapter: NewDyNamicAdapter

    companion object {
        fun newInstance(uId: String): UserDynamicFragment {
            return UserDynamicFragment().apply {
                arguments = Bundle().apply {
                    putString(Constants.TO_UID, uId)
                }
            }
        }
    }

    override fun getLayoutRes(): Int = R.layout.fragment_user_dynamic

    override fun initView() {
        mUid = arguments?.getString(Constants.TO_UID) ?: ""
        mPlayer = TXVodPlayer(activity)
        recycler_view.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        communityDynamicAdapter = NewDyNamicAdapter(null)
        recycler_view.adapter = communityDynamicAdapter
        setData()
        smart_view.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageNum++
                setData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1
                setData()
            }
        })

        communityDynamicAdapter.setIOnclickListener(object : NewDyNamicAdapter.NewCircrle {
            override fun clickVideo(container: FrameLayout, videoGroup: View, playView: TXCloudVideoView, img: ImageView, w: Int, h: Int,play :ImageView) {
                (activity as UserCenterActivity).addPlayerGroups(container, videoGroup, playView, img, w, h)
                if (playView.tag != flvUrl) {
                    if (null != rl_community_audio && null != rl_community_audio?.tag) {
                        rl_community_audio?.stopVoice()
                    }
                    mPlayer?.stopPlay(true)
                    mPlayer?.setPlayerView(playView)
                    mPlayer?.setAutoPlay(true)
                    mPlayer?.isLoop = true
                    flvUrl = playView.tag.toString()
                    mPlayer?.startPlay(flvUrl)

                    mPlayer?.setVodListener(object :ITXVodPlayListener {
                        override fun onNetStatus(p0: TXVodPlayer?, p1: Bundle?) {
                            play.visibility = View.GONE
                        }
                        override fun onPlayEvent(p0: TXVodPlayer?, p1: Int, p2: Bundle?) {
                            KLog.e("tag",p1.toString())
                            when(p1) {
                                TXLiveConstants.PLAY_EVT_PLAY_PROGRESS->{
                                    play.visibility = View.GONE
                                }
                            }
                        }
                    })

                } else {
                    mPlayer?.setPlayerView(playView)
                    mPlayer?.resume()
                }
            }

        })
        communityDynamicAdapter.addChildClickViewIds(R.id.tv_tip, R.id.tv_forward, R.id.tv_like, R.id.iv_love, R.id.tv_comment, R.id.rl_community_audio, R.id.im_gd)
        communityDynamicAdapter.setOnItemChildClickListener(itemChildClickListener)
        communityDynamicAdapter.setOnItemClickListener { adapter, view, position ->
            if (ClickUtil.canClick()) {
                my_position = position

                val intent = Intent(activity, DynamicDetailsActivity::class.java)
                intent.putExtra(Constants.DYNAMIC_BEAN, communityDynamicBeans[position])
                intent.putExtra("position", position.toString() + "")
                startActivityForResult(intent, 7)

            }
        }
        recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {

                    autoPlayVideo(recyclerView)

                    //   activity?.let { Glide.with(it).resumeRequests() };
                    KLog.e("tag", "停止滑动")


                } else {
                    //   activity?.let { Glide.with(it).pauseRequests() };
                    KLog.e("tag", "开始滑动")
                }

            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
                    lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                    visibleCount = lastVisibleItem - firstVisibleItem
                }
            }
        })
    }

    private fun autoPlayVideo(recyclerView: RecyclerView?) {
        var is_ture = false
        for (i in 0 until visibleCount) {
            KLog.e("tag", "循环$i")
            if (recyclerView != null && recyclerView.getChildAt(i) != null) {
                if (recyclerView.getChildAt(i).findViewById<View>(R.id.video_view) != null) {
                    is_ture = true
                    val homeGSYVideoPlayer = recyclerView.getChildAt(i).findViewById<TXCloudVideoView>(R.id.video_view)

                    val rect = Rect()
                    homeGSYVideoPlayer.getLocalVisibleRect(rect)
                    val videoheight = homeGSYVideoPlayer.height
                    if (rect.top == 0 && rect.bottom == videoheight) {

                        if (mPlayer?.isPlaying == true && flvUrl.equals(homeGSYVideoPlayer.tag.toString())) {
                            //如果视频正在播放并且url地址相同

                        } else {

                            if (null != rl_community_audio && null != rl_community_audio?.tag) {
                                rl_community_audio?.stopVoice()
                            }
                            mPlayer?.stopPlay(true)
                            mPlayer?.setPlayerView(homeGSYVideoPlayer)
                            mPlayer?.setAutoPlay(true)
                            mPlayer?.isLoop = true
                            flvUrl = homeGSYVideoPlayer.tag.toString()

                            mPlayer?.startPlay(flvUrl)

                            mPlayer?.setVodListener(object : ITXVodPlayListener {
                                override fun onPlayEvent(player: TXVodPlayer?, event: Int, param: Bundle?) {
                                    KLog.e("tag", event)
                                    if (event === TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
                                        homeGSYVideoPlayer.bringToFront()
                                    }
                                }

                                override fun onNetStatus(p0: TXVodPlayer?, p1: Bundle?) {
                                }
                            })
                        }
                        break
                    }
                }

//                if (null != recyclerView.getChildAt(i).findViewById<View>(R.id.rl_community_audio) && null != recyclerView.getChildAt(i).findViewById<View>(R.id.rl_community_audio).tag) {
//                    is_ture = true
//                    mPlayer?.stopPlay(true)
//                    rl_community_audio = recyclerView.getChildAt(i).findViewById<AudioMp3View>(R.id.rl_community_audio)
//                    rl_community_audio?.playVoice(recyclerView.getChildAt(i).findViewById<View>(R.id.rl_community_audio).tag.toString())
//                    communityDynamicAdapter.itemCount
//                    if (communityDynamicAdapter.itemCount < firstVisibleItem + i - 1) {
//                        communityDynamicAdapter.getItem(firstVisibleItem + i - 1).setmVoicePlaying(true)
//                    } else {
//                        if (communityDynamicAdapter.itemCount < firstVisibleItem + i - 2) {
//                            communityDynamicAdapter.getItem(firstVisibleItem + i - 2).setmVoicePlaying(true)
//                        }
//                    }
//
//                    break
//
//                }

            }
        }
        if (!is_ture) {
            if (null != rl_community_audio && null != rl_community_audio?.tag) {
                rl_community_audio?.stopVoice()
            }
            mPlayer?.stopPlay(true)
        }
    }

    private var rl_community_audio = activity?.let { AudioMp3View(it, "") }
    private val itemChildClickListener = OnItemChildClickListener { adapter, view, position ->

        val id = view.id

        //    KLog.e("tag",communityDynamicAdapter.getItem(position).getUserinfo().getUser_nickname()+"/"+position);
        if (id == R.id.rl_community_audio) {
            if (null != rl_community_audio && null != rl_community_audio?.tag) {
                rl_community_audio?.stopVoice()
            }
            mPlayer?.stopPlay(true)
            flvUrl = ""
            if (communityDynamicAdapter.getItem(position).ismVoicePlaying()) {


                communityDynamicAdapter.getItem(position).setmVoicePlaying(false)
            } else {
                rl_community_audio = view as AudioMp3View
                rl_community_audio?.playVoice(view.tag.toString())
                communityDynamicAdapter.getItem(position).setmVoicePlaying(true)


            }
        } else if (id == R.id.tv_comment) {//请你发言

            my_position = position
            val intent = Intent(activity, DynamicDetailsActivity::class.java)
            intent.putExtra(Constants.DYNAMIC_BEAN, communityDynamicBeans[position])
            intent.putExtra("position", position.toString() + "")
            startActivityForResult(intent, 7)

        } else if (id == R.id.tv_like) {//点赞
            addLike(communityDynamicAdapter.getItem(position).id,
                    communityDynamicAdapter.getItem(position).uid, position, view)
        } else if (id == R.id.im_gd) {
            arrayList.clear()
            if (communityDynamicBeans[position].uid.equals(CommonAppConfig.getInstance().uid)) {
                arrayList.add("删 除")
                arrayList.add("取 消")
                showpop(view, arrayList, communityDynamicBeans[position].id, 0)
            } else {
                arrayList.add("举报")
                arrayList.add("取 消")
                showpop(view, arrayList, communityDynamicBeans[position].id, 1)

            }


        }
    }
    private var mPopWindow: PopupWindow? = null
    private var mRecyclerView: RecyclerView? = null
    private var mAdapter: NewCirclePopAdapter? = null
    fun showpop(m_view: View, arrayList: List<String>, id: String, type: Int) {
        val contentView = LayoutInflater.from(activity).inflate(R.layout.dialog_pop_new_circle, null)
        mPopWindow = PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        mPopWindow?.run {
            setContentView(contentView)
            mRecyclerView = contentView.findViewById<RecyclerView>(R.id.rv_newlistview)
            mRecyclerView?.setHasFixedSize(true)
            mRecyclerView?.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
            mRecyclerView?.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            mAdapter = NewCirclePopAdapter(com.manor.dynamic.R.layout.rv_new_circle_item, arrayList)
            mRecyclerView?.adapter = mAdapter
            if (isShowing) {
                dismiss()
            } else {
                showAsDropDown(m_view)
            }
            mAdapter?.setOnItemClickListener(OnItemClickListener { adapter, view, position ->
                if (position == 0) {
                    if (type == 0) {
                        delDynamic(id)
                    } else {
                        stopVoice()
                        RouteUtil.forwardReport(2, id)
                    }

                }
                dismiss()
            })
        }
    }

    fun delDynamic(dynamicBean: String) {
        DynamicHttpUtil.delDynamic(dynamicBean, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0) {
                    pageNum++
                    setData()
                }
                ToastUtil.show(msg)
            }

        })
    }

    //点赞
    private fun addLike(id: String, uid: String, position: Int, view: View) {
        if (uid == CommonAppConfig.getInstance().uid) {
            ToastUtil.show(WordUtil.getString(com.manor.dynamic.R.string.video_comment_cannot_self))
            return
        }
        DynamicHttpUtil.addLike(id, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0) {
                    val result = PitUtil.strGetFirst(info)
                    val obj = JSON.parseObject(result)
                    //EventBus.getDefault().post(new DynamicLikeEvent(dynamicBean.getId(), obj.getIntValue("islike"), obj.getString("nums")));
                    val islike = obj.getIntValue("islike")
                    val nums = obj.getString("nums")
                    communityDynamicAdapter.getItem(position).islike = islike.toString() + ""
                    communityDynamicAdapter.getItem(position).likes = nums
                    communityDynamicBeans[position].islike = islike.toString()
                    communityDynamicBeans[position].likes = nums
                    //    communityDynamicAdapter.notifyItemChanged(position+1);
                    val tv_name = view as DrawableTextView
                    if ("1" == communityDynamicAdapter.getItem(position).islike) {
                        tv_name.leftDrawable = activity?.getDrawable(R.mipmap.icon_up)
                        tv_name.text = nums
                    } else if ("0" == communityDynamicAdapter.getItem(position).islike) {
                        tv_name.leftDrawable = activity?.getDrawable(R.mipmap.icon_unup)
                        tv_name.text = nums
                    }
                } else {
                    ToastUtil.show(msg)
                }
            }
        })
    }

    fun setData() {
        DynamicHttpUtil.getHomeDynamicList(mUid, pageNum, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                is_shuaxin = true
                if (code == 0) {
                    if (info.isNotEmpty()) {
                        if (pageNum > 1) {//加载
                            val communityDynamic = JSON.parseArray(info, CommunityDynamicBean::class.java)
                            communityDynamicAdapter?.addData(communityDynamic)
                            communityDynamicBeans?.addAll(communityDynamic)
                            smart_view.finishLoadMore()
                        } else {//刷新
                            if (communityDynamicBeans?.size > 0) {
                                communityDynamicBeans?.clear()
                            }

                            val communityDynamic = JSON.parseArray(info, CommunityDynamicBean::class.java)
                            communityDynamicBeans?.addAll(communityDynamic)
                            communityDynamicAdapter?.setNewInstance(communityDynamic)

                            //                    communityDynamicAdapter.setNewData(communityDynamicBeanList);
                            smart_view?.finishRefresh()
                        }
                    } else {
                        smart_view?.finishLoadMore()
                        smart_view?.finishRefresh()

                    }
                } else {
                    smart_view?.finishLoadMore()
                    smart_view?.finishRefresh()
                    ToastUtil.show(msg)
                }

                if (communityDynamicAdapter?.data.isNullOrEmpty()) {
                    communityDynamicAdapter?.setEmptyView(R.layout.view_empty_default)
                }

            }

            override fun onError() {
                super.onError()
                if (communityDynamicAdapter?.data.isNullOrEmpty()) {
                    communityDynamicAdapter?.setEmptyView(R.layout.view_empty_default)
                }
            }


        })
    }



    override fun onResume() {
        super.onResume()
        if((activity as UserCenterActivity).isOnclick==2&&!flvUrl.equals("")){
            mPlayer?.startPlay(flvUrl)
        }else{
            mAdapter?.notifyDataSetChanged()
        }

    }

    override fun onStop() {
        super.onStop()

        KLog.e("tag","onStop")
    }

    override fun onPause() {
        KLog.e("tag","onPause")
        stopVoice()
        super.onPause()

    }

    override fun onDestroy() {
        KLog.e("tag","onDestroy")
        stopVoice()
        super.onDestroy()
    }

    fun stopVoice() {
            mPlayer?.stopPlay(false)

        if (null != rl_community_audio && null != rl_community_audio?.tag) {
            rl_community_audio?.stopVoice()
            rl_community_audio?. resetView()
            rl_community_audio?. release()
        }
    }
}